<template>
  <CommonDialog
    v-model="visible"
    title="插入"
    :width="1000"
    submit-text="确定"
    @submit="submit"
    @cancel="cancel"
  >
    <nav class="nav-content">
      <li
        v-for="(item, index) in ['常规', 'QA']"
        :key="index"
        :class="{ active: index === navCurrent }"
        @click="navChange(index)"
      >
        {{ item }}模式
      </li>
    </nav>

    <div class="form-content">
      <Form ref="formEl" :model="formData" :rules="rules" :label-width="40" label-position="top">
        <FormItem v-if="!navCurrent" label="内容" prop="content">
          <Input
            v-model="formData.content"
            type="textarea"
            placeholder="请输入内容"
            class="content-input"
          />
        </FormItem>

        <template v-else>
          <FormItem label="问题" prop="content">
            <Input v-model="formData.content" type="textarea" placeholder="请输入问题" :rows="12" />
          </FormItem>

          <FormItem label="答案" prop="content">
            <Input v-model="formData.answer" type="textarea" placeholder="请输入答案" :rows="12" />
          </FormItem>
        </template>
      </Form>

      <div class="index-content">
        <div class="header-info">
          <span>数据索引({{ indexList.length }})</span>

          <Button @click="addIndex">新增</Button>
        </div>

        <ul class="index-list">
          <li v-for="(item, index) in indexList" :key="index">
            <div class="title-row">
              <span>{{item.name || '自定义索引' }}</span>
              <Icon v-if="item.name !== '默认索引'" type="ios-trash" @click="indexList.splice(index, 1)" />
            </div>
            <Input ref="indexInputRef" v-model="item.value" type="textarea" :rows="2" :readonly="item.name === '默认索引'" />
          </li>
        </ul>
      </div>
    </div>
  </CommonDialog>
</template>

<script setup>
import { onMounted, ref, nextTick, inject } from 'vue'
import { Message } from 'view-ui-plus'

import { fileContent } from '@/api/modules/knowledgeBase'

const emit = defineEmits(['cancel', 'submit'])

const props = defineProps({
  tableId: [Number, String]
})
const getTypeId = inject('getTypeId')
// 是否打开弹窗
const visible = ref(true)

// 加载状态
const loading = ref(false)

const dataId = ref(undefined)
// 表单元素ref
const formEl = ref(null)
// 表单数据
const formData = ref({
  answer: '',
  content: ''
})

const navCurrent = ref(0)

// 表单校验条件
const rules = ref({
  content: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
  answer: [{ required: true, message: '内容不能为空', trigger: 'blur' }]
})

const navChange = (index) => {
  navCurrent.value = index
}

const getIndexOption = () => {
  return {
    value: ''
  }
}

const indexInputRef = ref([])
const indexList = ref([])
const addIndex = () => {
  indexList.value.unshift(getIndexOption())
  nextTick(() => {
    indexInputRef.value[0].focus()
  })
}

const disposeIndex = () => {
  const { content, answer } = formData.value

  const defaultIndexList = [
    {
      value: content
    }
  ]

  if (navCurrent.value === 1) {
    defaultIndexList.push({
      value: answer
    })
  }

  const setedIndexList = [...indexList.value, ...defaultIndexList].reduce((pre, cur) => {
    return cur.value && pre.includes(cur.value) ? pre : [...pre, cur.value]
  }, [])

  return setedIndexList.map((item) => {
    return {
      name: [content, answer].includes(item) ? '默认索引' : '自定义索引',
      value: item
    }
  })
}

/**
 * 提交表单
 */
const submit = async () => {
  let valid = await formEl.value.validate()
  if (!valid) return

  loading.value = true

  const { content, answer } = formData.value

  try {
    const params = {
      content,
      answer: navCurrent.value ? answer : '',
      indexList: disposeIndex(),
      id: dataId.value,
      attid: props.tableId,
      serviceid: getTypeId()
    }

    await fileContent.insert({
      data: params
    })

    Message.success('操作成功')
    emit('submit')
  } catch (error) {
    console.error(error)
  }

  loading.value = false
}

/**
 * 取消表单
 */
const cancel = () => {
  emit('cancel')
}

const initData = (data = {}) => {
  dataId.value = data.id
  console.log(data)

  if (data.id) {
    getDetail()
  }
}

const getDetail = () => {
  fileContent
    .detail({
      data: {
        id: dataId.value
      }
    })
    .then(({ data }) => {
      formData.value.answer = data.answer
      formData.value.content = data.content
      indexList.value = data.indexList
      navCurrent.value = data.answer ? 1 : 0
    })
}

defineExpose({
  initData
})
</script>

<style scoped lang="scss">
:deep(.ivu-input) {
  resize: none;
}
:deep(.ivu-form-item) {
  .ivu-form-item-label {
    padding: 8px 0 18px;
  }
}

:deep(.ivu-form-item-content) {
  margin-left: 0 !important;
}

.nav-content {
  display: flex;
  align-items: center;
  background-color: #f7f8fa;
  border: 1p solid #e8ebef;
  border-radius: 4px;
  padding: 3px;
  width: fit-content;
  li {
    list-style: none;
    padding: 4px 16px;
    cursor: pointer;
    &:nth-child(n + 2) {
      margin-left: 8px;
    }
    &:hover {
      color: #3370ff;
    }
    &.active {
      background-color: #fff;
      border-radius: 4px;
      color: #3370ff;
    }
  }
}

.form-content {
  display: flex;
  margin-top: 16px;
  .ivu-form {
    flex: 1;
    .content-input {
      :deep(.ivu-input) {
        height: 580px !important;
      }
    }
    .ivu-form-item {
      margin-bottom: 0;
      &:nth-child(2) {
        margin-top: 16px;
      }
    }
  }
  .index-content {
    width: 440px;
    margin-left: 24px;
    .header-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .index-list {
      max-height: 586px;
      overflow-y: auto;
      > li {
        background-color: #fbfbfc;
        border: 1px solid #dfe2e9;
        padding: 16px;
        border-radius: 6px;
        margin-top: 8px;
        &:hover {
          .title-row .ivu-icon-ios-trash{
            display: block;
          }
        }
        .title-row {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;
          .ivu-icon-ios-trash {
            cursor: pointer;
            font-size: 18px;
            display: none;
            &:hover {
              opacity: .8;
            }
          }
        }
        :deep(.ivu-input) {
          border: none;
          background-color: unset;
          padding: 0;

          &:focus {
            background-color: #fff;
            padding: 4px;
          }
        }
      }
    }
  }
}
</style>
